const OpenAi = require('openai');
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const storage = multer.diskStorage({
    destination: './gpt',
    filename: (req, file, cb) => {
        cb(null, req.body.fileName)
    }
})
const upload = multer({ storage })

const API_KEY = "sk-xsAp4gBwl3IxYYLz0d3961DeA9A1462eA7Ea2bE137A12308";
const app = express();
app.use(cors())
app.use(express.json());

const openai = new OpenAi({
    apiKey: API_KEY,
    baseURL: "https://openkey.cloud/v1" //如果是代理的key，就写地址，如果是官网的就不用写
})

const langs = {
    "cn": "中文",
    "en": "英文",
    "ja": "日语"
}
const messages = [];
async function generateText(message, res) {
    const completion = await openai.chat.completions.create({
        model: "gpt-4o",
        // messages数组上下文联系，上文，当前文
        messages: [
            ...messages,
            {
                role: "user",
                content: message
            }
        ],
        stream: true
    })
    messages.push({ role: "user", content: message });
    const assistanceMsg = { role: "assistant", content: "" }
    for await (const chunk of completion) {
        if (chunk) {
            const content = chunk['choices'][0].delta.content || ""
            res.write(content);
            assistanceMsg.content += content
        }
    }
    messages.push(assistanceMsg);
}
// 问答
app.post('/chat', async (req, res) => {
    const { message } = req.body;
    console.log(message);
    await generateText(message, res)
    res.end()
})
// 文本翻译
app.get("/text/translate", async (req, res) => {
    const { message, lan } = req.query;
    if (langs[lan]) {
        const mes = `Translate the following text to ${langs[lan]}: ${message}`
        await generateText(mes, res)
        res.end()
    } else {
        res.end("请选择语言")
    }
})
// 文本纠错
app.get("/text/correct", async (req, res) => {
    const { message } = req.query;
    const mes = `文本纠正："${message}"`
    console.log(mes);
    await generateText(mes, res)
    res.end()
})
// 图片生成
app.post("/create/image", async (req, res) => {
    const { message } = req.body;
    console.log(message);
    if (!message) return;
    const image = await openai.images.generate({
        model: "dall-e-2",
        prompt: message,
        n: 1,//一次生成一条
        size: "256x256",
    })

    if (image.error) {
        res.json({ error: image.error.message })
    } else {
        res.json({ image: image.data[0].url })
    }
})
// 文字转语音
app.post("/create/audio", async (req, res) => {
    const { message } = req.body;
    console.log(message);
    if (!message) return;
    const mp3 = await openai.audio.speech.create({
        model: "tts-1",
        voice: "alloy",
        input: message,
    });
    res.setHeader('Content-Type', 'audio/wav');
    const buffer = Buffer.from(await mp3.arrayBuffer());
    res.send(buffer);

})
// 语音转文字
app.post("/audio/text", upload.single('file'), async (req, res) => {
    try {
        transcription = await openai.audio.transcriptions.create({
            model: "whisper-1",
            file: fs.createReadStream(path.resolve(__dirname, req.body.fileName))
        })
        res.json({ text: transcription.text })
    } catch (error) {
        console.log(error);
    }
})
// 语音翻译
app.post("/audio/translate", upload.single('file'), async (req, res) => {
    try {
        transcription = await openai.audio.translations.create({
            model: "whisper-1",
            file: fs.createReadStream(path.resolve(__dirname, req.body.fileName))
        })
        res.json({ text: transcription.text })
    } catch (error) {
        console.log(error);
    }
})
// 图片想象
app.post("/image/text", upload.single('file'), async (req, res) => {

    const { fileName, text } = req.body
    console.log(fileName, text);
    image_file = fs.readFileSync(path.resolve(__dirname, fileName))
    try {
        const response = await openai.chat.completions.create({
            model: "gpt-4o",
            messages: [
                {
                    role: "user",
                    content: [
                        { type: "text", text },
                        {
                            type: "image_url",
                            image_url: {
                                "url": `data:image/png;base64,${image_file.toString("base64")}`,
                            },
                        },
                    ],
                },
            ],
        });
        res.send({ message: response.choices[0].message.content })
        console.log(response.choices[0]);
    }
    catch (error) {
        console.log(error);
    }
}
)
app.listen(3000, () => {
    console.log("server is running on port 3000");
})